﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
//using System.Diagnostics;//Process
using EShop.BLL;
using EShop.Common;
using SQLDMO;
//using System.Runtime.InteropServices;
//ALTER DATABASE [数据库名] SET OFFLINE WITH ROLLBACK IMMEDIATE
namespace EShop.Client
{
    public partial class frmDatabaseBackupOrRestore : Form
    {
        public frmDatabaseBackupOrRestore()
        {
            InitializeComponent();
        }

        DbOperationBLL oDbOperationBLL = new DbOperationBLL();

        private void frmDatabaseBackupOrRestore_Load(object sender, EventArgs e)
        {
            
        }

        private void btnBackupBegin_Click(object sender, EventArgs e)
        {
            lblBackupMsg.Visible = true;
            string path = txtBackupPath.Text.Trim();
            if (string.IsNullOrEmpty(path))
            {
                lblBackupMsg.Text = path + "请选择备份路径";
                this.btnBackupBroswer.Focus();
                return;
            }

            lblBackupMsg.Visible = false;
            DataBackup();
        }

        private void btnRestoreBegin_Click(object sender, EventArgs e)
        {
            lblRestoreMsg.Visible = false;
            string path = txtRestorePath.Text.Trim();
            if (string.IsNullOrEmpty(path))
            {
                lblRestoreMsg.Visible = true;
                lblRestoreMsg.Text = "请选择恢复文件路径";
                this.btnRestoreBroswer.Focus();
                return;
            }
            DataRetore();
            System.Windows.Forms.Application.Restart();
        }

        private void btnBackupBroswer_Click(object sender, EventArgs e)
        {
            
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "备份文件|*.bak";
            saveFileDialog.FileName = "(eShop)Backup(" + DateTime.Now.ToString("yyyyMMddhhmmss") + ")";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtBackupPath.Text = saveFileDialog.FileName;
            }
        }

        private void btnRestoreBroswer_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "备份文件(*.bak)|*.bak|所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtRestorePath.Text = openFileDialog.FileName;
            }
        }

        private string server = ".";
        private string uid = "sa";
        private string pwd = "201314";
        private string database = "eShop";
        SQLDMO.Backup backup;
        SQLDMO.Restore restore;

        private void DataBackup()
        {
            backup = new Backup();
            SQLDMO.SQLServer sqlServer = new SQLServer();
            this.progressBar1.Visible = true;
            this.lblPercent.Visible = true;
            backup.PercentComplete+=new BackupSink_PercentCompleteEventHandler(PercentComplete);
            try
            {
                progressBar1.Value = 0;
                lblPercent.Text = "0%";
                sqlServer.LoginSecure = false;
                sqlServer.Connect(server, uid, pwd);
                //sqlServer.
                backup.Action = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                backup.Database = database;
                string backupPath = txtBackupPath.Text;
                backupPath = backupPath.Replace('[', '【');
                backupPath = backupPath.Replace(']', '】');
                backup.Files = string.Format("[{0}]", backupPath);
                backup.BackupSetName = "eShop";
                backup.BackupSetDescription = "Database Backup";
                backup.Initialize = true;
                backup.PercentCompleteNotification = 1;
                backup.SQLBackup(sqlServer);
                progressBar1.Value = 100;
                MessageBox.Show("数据库备份完成！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库备份失败！请检查指定的备份路径及文件名是否合法。\n具体原因：\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                sqlServer.DisConnect();
                backup.PercentComplete -= new BackupSink_PercentCompleteEventHandler(PercentComplete);
                backup = null;
            }
        }

        private void DataRetore()
        {
            restore = new Restore();
            SQLServer sqlServer = new SQLServer();
            restore.PercentComplete += new RestoreSink_PercentCompleteEventHandler(PercentComplete);
            this.progressBar1.Visible = true;
            this.lblPercent.Visible = true;
            try
            {
                progressBar1.Value = 0;
                lblPercent.Text = "0%";
                sqlServer.LoginSecure = false;
                sqlServer.Connect(server, uid, pwd);
                restore.Action = SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;

                #region 排他操作
                SQLDMO.QueryResults qr = sqlServer.EnumProcesses(-1);
                int iColPIDNum = -1;
                int iColDbName = -1;
                for (int i = 1; i <= qr.Columns; i++)
                {
                    string strName = qr.get_ColumnName(i);
                    if (strName.ToUpper().Trim() == "SPID")
                    {
                        iColPIDNum = i;
                    }
                    else if (strName.ToUpper().Trim() == "DBNAME")
                    {
                        iColDbName = i;
                    }
                    if (iColPIDNum != -1 && iColDbName != -1)
                        break;
                }
                for (int i = 1; i <= qr.Rows; i++)
                {
                    int lPID = qr.GetColumnLong(i, iColPIDNum);
                    string strDBName = qr.GetColumnString(i, iColDbName);
                    if (strDBName.ToUpper() == database.ToUpper())
                    {
                        sqlServer.KillProcess(lPID);
                    }
                }
                #endregion

                restore.Database = database;
                restore.Files = string.Format("[{0}]", txtRestorePath.Text.Trim());
                restore.ReplaceDatabase = true;
                restore.PercentCompleteNotification = 1;
                restore.SQLRestore(sqlServer);
                progressBar1.Value = 100;
                MessageBox.Show("数据库恢复完成！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库恢复失败！请检查指定的备份路径及文件名是否合法。\n具体原因：\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                sqlServer.DisConnect();
            }
            restore.PercentComplete -= new RestoreSink_PercentCompleteEventHandler(PercentComplete);
            restore = null;
        }
       

        private void PercentComplete(string message, int percent)
        {
            char[] a = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            int startPos = message.IndexOfAny(a);
            int endPos = message.LastIndexOfAny(a);
            int value = Convert.ToInt32(message.Substring(startPos, endPos - startPos + 1));
            progressBar1.Value = value;
            lblPercent.Text = progressBar1.Value.ToString() + "%";
            System.Windows.Forms.Application.DoEvents();
        }
    }
}
